//
//  GDTansitionModelDate.m
//  GraduationDesign
//
//  Created by JiaKang.Zhong on 16/1/4.
//  Copyright © 2016年 JiaKang.Zhong. All rights reserved.
//

#import "GDTansitionModelDateOperation.h"
#import  <AFNetworking.h>
#import "GDBusStationController.h"
#import "GDWeatherController.h"
#import "GDNowWeatherModel.h"
#import "GDTrainStationController.h"
#import "GDTrainTicketModel.h"
#import "GDTrainInformationModel.h"
#import "GDTrainViewModel.h"
#import "GDBusStationNumber.h"
#import "GDBusLineViewController.h"
#import "GDNowBusModel.h"
#import "GDBusStationNumberController.h"
#import "GDBusStatsViewController.h"
#import "GDBusStationNumber.h"
#import "MBProgressHUD+MJ.h"
@interface GDTansitionModelDateOperation (){
    
}

@end
static AFHTTPRequestOperationManager *AFManager;

@implementation GDTansitionModelDateOperation

-(instancetype) init{
    if (self = [super init]) {
        if (!AFManager) {
            AFManager = [AFHTTPRequestOperationManager manager];
        }
    }
    return self;
}


+(instancetype) initObj{
    return [[self alloc ] init];
}


#pragma mark 显示天气信息
+(void)initDateWithWeather:(id)delegate success:(void (^)(GDWeatherModelCenter *))success failure:(void (^)(NSError *))failure{

    [self initObj];
    GDWeatherController * _delegate = delegate;
    /**
        *  cityname 	string 	Y 	城市名或城市ID，如："苏州"，需要utf8 urlencode
           dtype        string 	N 	返回数据格式：json或xml,默认json
           format       int 	N 	未来6天预报(future)两种返回格式，1或2，默认1
           key          string 	Y 	你申请的key
     */
    NSString * url = @"http://v.juhe.cn/weather/index";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    param[@"key"] = DGWeatherAppKey;
    param[@"cityname"] = _delegate.cityName ;//@"珠海"
    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%@",[NSThread currentThread]);
        GDLog(@"%@",responseObject);
        NSDictionary * resultDic = responseObject[@"result"];
        /**
         *  将数据写入到模型中
         */
        if ([responseObject[@"error_code"] intValue]) {
            ShowErrorAlert(responseObject[@"reason"]);
            success(nil);
            return ;
        }
        NSDictionary * skDic = resultDic[@"sk"];//当前实时的天气
        NSDictionary * todayDic = resultDic[@"today"];// 今天的天气
        NSDictionary * futureDic = resultDic[@"future"];// 未来的天气的天气
        //  现在的天气模型
        NSDictionary * stringReusltDic = [self stringByDictionary:skDic :todayDic];
        GDNowWeatherModel * nowModel = [GDNowWeatherModel currWeatherWithDictionary:stringReusltDic];
        /**
         *   未来的天气模型   根据day_日期格式的形式来获取值。获取三天的天气状况
                            day_20160107
         day_20160108 = {
         temperature = 14℃~19℃;
             weather_id = {
             fa = 01;
             fb = 01;
         };
             wind = 微风;
             week = 星期五;
             date = 20160108;
             weather = 多云;
         };
         */
       // 天气模型数组
        NSArray * arrayModel = [self getFutureWeatherModelWithDic:futureDic];
        //模型组合
        GDWeatherModelCenter  * weatherModelCenter = [GDWeatherModelCenter weatherWithModel:nowModel and:arrayModel];
        
        if (success) {
            success(weatherModelCenter);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%@",error);
        if (error) {
            failure(error);
        }
       
    }];
    
}


#pragma mark 将返回两个结果的Dictionary拼接为一个
+(NSDictionary *) stringByDictionary:(NSDictionary * ) dic_1 :(NSDictionary *) dic_2{
    NSArray * dic_1_key = [dic_1 allKeys];
    NSArray * dic_1_value = [dic_1 allValues];
    NSArray * dic_2_key = [dic_2 allKeys];
    NSArray * dic_2_value = [dic_2 allValues];
    NSMutableDictionary * dicM = [NSMutableDictionary dictionary];
    unsigned long index = 0;
    for (int i = 0; i < dic_1_key.count + dic_2_key.count; i++) {
        if (i < dic_1_key.count) {
//            对dic_1进行操作
            [dicM setObject:dic_1_value[i] forKey:dic_1_key[i]];
        }else{
            index = i - dic_1_key.count;
//            对二进行操作
              [dicM setObject:dic_2_value[index] forKey:dic_2_key[index]];
        }
    }
    return dicM;
    
}


#pragma mark 获取未来天气的字典，并转换为模型数组
+(NSArray *) getFutureWeatherModelWithDic:(NSDictionary *) futureDic{
    
    NSArray * dateArray = [self getFutureDate];
    NSMutableArray * arrayM = [NSMutableArray array];
    for (int index = 0; index < dateArray.count; index++) {
         NSDictionary * Dic = futureDic[dateArray[index]];
        GDFutureWeatherModel * Model = [GDFutureWeatherModel futureWeatherWithDictionary:Dic];
        [arrayM addObject:Model];
    }
    return [arrayM copy];
}


#pragma mark 获取今、名、后、大后天得日期 day_20160108      改动为，未来五天
+(NSArray *) getFutureDate{
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
//    NSDate * now = [[NSDate alloc] init];
    //  今天
//    NSString * today = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:now]];
    //  明天
    NSTimeInterval secondDay = 24 * 60 * 60;
    NSDate * tomorrowDate = [NSDate dateWithTimeIntervalSinceNow:secondDay];
    NSString * tomorrow = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:tomorrowDate]];
    // 后天
    NSTimeInterval threeDay = 24 * 60 * 60 * 2;
    NSDate * threeDayDate = [NSDate dateWithTimeIntervalSinceNow:threeDay];
    NSString * dayAfterTomorrow = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:threeDayDate]];
//    大后天
    NSTimeInterval fourDay = 24 * 60 * 60 * 3;
    NSDate * fourDayDate = [NSDate dateWithTimeIntervalSinceNow:fourDay];
    NSString * threeDaysFromToday = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:fourDayDate]];
    //    第五天
    NSTimeInterval fiveDay = 24 * 60 * 60 * 4;
    NSDate * fiveDayDate = [NSDate dateWithTimeIntervalSinceNow:fiveDay];
    NSString * fiveDayDaysFromToday = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:fiveDayDate]];
    //    第六天
    NSTimeInterval sixDay = 24 * 60 * 60 * 5;
    NSDate * sixDayDate = [NSDate dateWithTimeIntervalSinceNow:sixDay];
    NSString * sixFromToday = [NSString stringWithFormat:@"day_%@",[formatter stringFromDate:sixDayDate]];
    return @[tomorrow,dayAfterTomorrow,threeDaysFromToday,fiveDayDaysFromToday,sixFromToday];
}



#pragma mark 显示该公交有多少条路线
+(void)initDatewithBusStationNumber:(id)delegate success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure{
    
    GDBusStationNumberController * stationNumberController = delegate;
    AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
    NSString * url = @"http://www.zhbuswx.com/BusLine/WS.asmx/SearchLine";
    AFManager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary * dictM = @{@"key":stationNumberController.busLineNumber};
    [AFManager POST:url parameters:dictM success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
         GDLog(@"%s %@ %@",__func__,responseObject,[NSThread currentThread]);
        NSMutableArray * arrayM = [NSMutableArray array];
        NSArray * modelArray = responseObject[@"d"];
        for (NSDictionary * dic in modelArray) {
            GDBusStationNumber * stationModel  = [GDBusStationNumber stationBusWithDic:dic];
            [arrayM addObject:stationModel];
        }
        if (success) {
            success([arrayM copy]);
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        if (error) {
            failure(error);
        }
    }];

}


#pragma mark 显示该公交具体经过路线
+(void)initDateWithBusStationLine:(id)delegate success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure{
    GDBusLineViewController * _delegate = delegate;
    AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
//    /**
//     *  	key     string	是	应用APPKEY(应用详细页查询)
//            city    string	是	需要查询的城市，所有支持的城市由接口1提供。
//            q       string	是	待查询的线路，如： 110，快线1号
//     */
//    //    http://api.juheapi.com/bus/line?key=您申请的appkey&city=苏州&q=110
//    NSString * url = @"http://api.juheapi.com/bus/line";
//    NSMutableDictionary * param = [NSMutableDictionary dictionary];
//    param[@"key"] = DGBusStationAppKey;
//    param[@"city"] =  @"珠海";
//    param[@"q"] =  @"204";
//    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        GDLog(@"%s %@ %@",__func__,responseObject,[NSThread currentThread]);
//        NSArray * resultArray = responseObject[@"result"];
//        /**
//         *  A -- B  的公交路线      B -- A  的公交路线
//         */
//        GDBusStationLinesModel * busStationModel = [GDBusStationLinesModel statsWithAarray:resultArray];
//        if (success) {
//            success(busStationModel);
//        }
//    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
//        GDLog(@"%s %@ ",__func__,error);
//        if (error) {
//            failure(error);
//        }
//        
//    }];

    
    NSString * url = @"http://www.zhbuswx.com/BusLine/WS.asmx/LoadStationByLineId";
    AFManager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary * dictM = @{@"lineId":_delegate.busModel.Id};// 测试值 @"305b2d5a-a551-4ff6-b7ba-14ae64ea2aea"
    [AFManager POST:url parameters:dictM success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%s %@ %@",__func__,responseObject,[NSThread currentThread]);
        NSMutableArray * arrayM = [NSMutableArray array];
        NSArray * modelArray = responseObject[@"d"];
        for (NSDictionary * dic in modelArray) {
            GDBusStationLinesModel * stationModel  = [GDBusStationLinesModel statsWithAarray:dic];
            [arrayM addObject:stationModel];
        }
         if (success) {
            success([arrayM copy]);
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        if (error) {
            failure(error);
        }
    }];

   
}


#pragma mark 获取实时公交信息
+(void)initDateWithNowBusSationLocation:(id)delegate success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure{
       AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
    GDBusLineViewController * lineController = delegate;
    GDBusStationNumber * busModel = lineController.busModel;
    NSString * url = @"http://www.zhbuswx.com/BusLine/WS.asmx/GetBusListOnRoad";
    AFManager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary * dictM = @{@"lineName":busModel.LineNumber,@"fromStation":busModel.FromStation};
    [AFManager POST:url parameters:dictM success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%s %@ ",__func__,responseObject);
        NSMutableArray * arrayM = [NSMutableArray array];
        NSArray * modelArray = responseObject[@"d"];
            for (NSDictionary * dic in modelArray) {
                GDNowBusModel * stationModel  = [GDNowBusModel currentStationWithDic:dic];
                [arrayM addObject:stationModel];
            }
            if (success) {
                success([arrayM copy]);
            }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        if (error) {
            failure(error);
        }
    }];
    

}

#pragma mark 获取公交站点信息
+(void)initDateWithBusStationStats:(id)delegate success:(void (^)(GDBusStationStatsModel *))success failure:(void (^)(NSError *))failure{
     [self initObj];
    GDBusStatsViewController * _delegate = delegate;

    NSString * url = @"http://api.juheapi.com/bus/stat";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    /**
     *  	key     string	是	应用APPKEY(应用详细页查询)
            city	string	是	需要查询的城市，所有支持的城市由接口1提供。
            q       string	是	待查询的站台名称，如： 西直门
     */
    param[@"key"] = DGBusStationAppKey;
    param[@"city"] = _delegate.cityName;//
    param[@"q"] =  _delegate.statsName;//@"湖心路口";
    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%s %@ %@",__func__,responseObject,[NSThread currentThread]);
        NSDictionary * resultDic =  [responseObject[@"result"] lastObject];
        if (!resultDic) {
            ShowErrorAlert(responseObject[@"reason"]);
            if (success) {
                success(nil);
            }
        }else{
            GDBusStationStatsModel * statsModel = [GDBusStationStatsModel statWithDic:resultDic];
            if (success) {
                success(statsModel);
            }
        }
        
       
      
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        if (error) {
            failure(error);
        }
    }];
    
   
}


#pragma mark 获取周围的公交信息
+(void)initDateWithBUsStationLocation:(id)delegate success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure{
    GDBusStationController * _delegate = delegate;
    AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
    NSString * url = @"http://api.juheapi.com/bus/nearby";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    /**
     *  	key     string	是	应用APPKEY(应用详细页查询)
            city	string	是	需要查询的城市，所有支持的城市由接口1提供。
            lat     double	是	起点纬度
            lng     double	是	起点经度
            dist	int     否	查询半径
     */
    param[@"key"]  = DGBusStationAppKey;
    param[@"city"] = _delegate.cityName ; //@"珠海";//
    param[@"lat"]  = [_delegate.location valueForKey:@"latitude"];// @"22.1314";//
    param[@"lng"]  =  [_delegate.location valueForKey:@"longitude"];//@"113.35106";//
    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
          GDLog(@"%s %@ %@",__func__,responseObject,[NSThread currentThread]);
        NSMutableArray * arrayM = [NSMutableArray array];
        for(NSDictionary * dic in responseObject[@"result"]) {
             GDBusStationLocationModel * locationModel = [GDBusStationLocationModel locationWithDic:dic];
            [arrayM addObject:locationModel];
        }
        if (success) {
            success([arrayM copy]);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        if (error) {
            failure(error);
        }
    }];
    
}


#pragma mark 获取列车信息
+(void)initDateWithTrainStation:(id)delegate success:(void (^)(NSArray *))success failure:(void (^)(NSError *))failure{
 
    GDTrainStationController * _delegate = delegate;
    AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
    NSString * url = @"http://apis.juhe.cn/train/yp";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    /**
     key 	string 	是 	应用APPKEY(应用详细页查询)
     dtype 	string 	否 	返回数据的格式,xml或json，默认json
     from 	string 	是 	出发站,如：上海虹桥
     to 	string 	是 	到达站,如：温州南
     date 	string 	否 	出发日期，默认今日
     tt 	string 	否 	车次类型，默认全部，如：G(高铁)、D(动车)、T(特快)、Z(直达)、K(快速)、Q(其他)
     */
    param[@"key"]  = DGTrainAppKey;
    param[@"from"] =  _delegate.startName.text;//@"深圳北";//
    param[@"to"]  =  _delegate.endName.text;//@"广州南";//
    param[@"date"]  = _delegate.startTime;//@"2016-03-28";//
    NSMutableArray * arrayM = [NSMutableArray array];
    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%s %@  %@",__func__,responseObject,[NSThread currentThread]);
        NSArray * trainArray = responseObject[@"result"];
    
        /**
         * 列车模型
         */
        if ([responseObject[@"error_code"] intValue]) {
            ShowErrorAlert(responseObject[@"reason"]);
            success(nil);
            return ;
        }
      
        if(trainArray.count){
            for (NSDictionary * model in trainArray) {
                GDTrainInformationModel * ticketModel = [GDTrainInformationModel trainInformationWithDic:model];
                GDTrainViewModel * viewModel = [[GDTrainViewModel alloc] init];
                viewModel.model = ticketModel;
                [arrayM addObject:viewModel];
            }
            if(success){
                success(arrayM);
            }

        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        failure(error);
    }];
    
}




#pragma mark 获取票价模型
+(void) getTrainsTicketModel:(NSString *) train_no and:(NSString * ) from_station_no and:(NSString *) to_station_no and:(void(^)(GDTrainTicketModel *model)) success{
    
    AFHTTPRequestOperationManager *AFManager  = [AFHTTPRequestOperationManager manager];
    NSString * url = @"http://apis.juhe.cn/train/ticket.price.php";
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    /**
     train_no           string	是	列次编号，对应12306订票①：查询车次中返回的train_no
     from_station_no	string	是	出发站序号，对应12306订票①：查询车次中返回的from_station_no
     to_station_no      string	是	出发站序号，对应12306订票①：查询车次中返回的to_station_no
     date               date	否	默认当天，格式：2014-12-25
     key                string	是	应用APPKEY(应用详细页查询)
     */
    
    param[@"key"]  = DGTrainAppKey;
     param[@"train_no"]  = train_no;
    param[@"from_station_no"] =  from_station_no;
    param[@"to_station_no"]  =  to_station_no;
    [AFManager GET:url parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        GDLog(@"%s %@ ",__func__,[NSThread currentThread]);
        NSDictionary * trainDic = responseObject[@"result"];
        GDTrainTicketModel * model = [GDTrainTicketModel trainWithDic:trainDic];
         if (success) {
            success(model);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        GDLog(@"%s %@ ",__func__,error);
        
    }];
    
}



@end
